﻿using Cl.Model.Results;
using Cl.Repository;
using Cl.Service.Service.System.UploadFile;
using Cl.Utils.Helper;
using Cl.Utils;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BaseGoodsEntity = Cl.Entity.DataBaseEntity.Goods.BaseGoods;
using Cl.Model.DataBaseEntityDtos.Goods.BaseGoods;
using Cl.Utils.Helper.AutoMap;
using NetTaste;
using Cl.Utils.Primitives.Const;
using Cl.Utils.Primitives.Const.Goods;
using Microsoft.AspNetCore.Mvc;

namespace Cl.Service.Service.Goods.BaseGoods
{
    public class BaseGoodsService : IBaseGoodsService
    {
        private readonly ClRepository<BaseGoodsEntity> BaseGoodsRepository;
        private readonly IFileService FileService;
        public BaseGoodsService(ClRepository<BaseGoodsEntity> baseGoodsRepository, IFileService fileService)
        {
            BaseGoodsRepository = baseGoodsRepository;
            FileService = fileService;
        }


        public async Task<ResultInfoModel> Delete(List<int> ids)
        {
            if (ids == null || ids.Count <= 0)
                return GetResult.Error("参数不能为null");

            try
            {
                //数据准备
                var result = await BaseGoodsRepository.AsUpdateable(new BaseGoodsEntity() { DeletedId = GlobalUserManager.UserId, DeleteTime = DateTime.Now })
                    .UpdateColumns(it => new { it.DeletedId, it.DeleteTime })
                    .Where(x => ids.Contains(x.Id)).ExecuteCommandAsync();
                return GetResult.Success();
            }
            catch (Exception ex)
            {
                LoggerHelper.TryCatch(ex);
                return GetResult.Error(ex.Message);
            }
        }


        public async Task<PageResultModel<BaseGoodsOutputDto>> Query(SearchBaseGoodsDto request)
        {
            RefAsync<int> total = 0;
            var response = new PageResultModel<BaseGoodsOutputDto>
            {
                Result = new List<BaseGoodsOutputDto>()
            };

            var sql = BaseGoodsRepository.AsQueryable()
                .Includes(c => c.CreateUser)
                .Includes(up => up.UpdateUser);

            sql.WhereIF(!string.IsNullOrEmpty(request.Title), x => x.Title.Contains(request.Title));
            sql.WhereIF(!string.IsNullOrEmpty(request.AuditState), x => x.AuditState.Contains(x.AuditState));

            sql.OrderBy(p => p.CreateTime, OrderByType.Desc);
            // 计算开始和结束索引
            List<BaseGoodsEntity> list;
            if (request.IsPage)
            {
                list = await sql.ToPageListAsync(request.PageIndex, request.PageSize, total);
            }
            else
            {
                list = await sql.ToListAsync();
                total = list.Count;
            }

            response.TotalCount = total;
            response.Result = list.Select(x => new BaseGoodsOutputDto(x) { }).ToList();

            return response;


        }

        public async Task<ResultInfoModel> Save(BaseGoodsInputDto obj)
        {
            try
            {
                if (obj == null)
                    return GetResult.Error("参数不能null");

                //数据准备
                var operationData = obj.MapTo<BaseGoodsInputDto, BaseGoodsEntity>();
                operationData.CreateId = GlobalUserManager.UserId;
                operationData.CreateTime = DateTime.Now;
                operationData.AuditState = ProductStateConst.Offline;
                var result = await BaseGoodsRepository.AsInsertable(operationData).ExecuteReturnEntityAsync();
                if (result.Id != 0)
                    return GetResult.Success(string.Empty, operationData);
                return GetResult.Error("操作失败");
            }
            catch (Exception ex)
            {
                LoggerHelper.TryCatch(ex);
                return GetResult.Error(ex.Message);
            }
        }


        public async Task<ResultInfoModel> Update(BaseGoodsInputDto obj)
        {
            try
            {
                if (obj == null)
                    return GetResult.Error("参数不能为null");
                if (obj.Id == 0)
                    return GetResult.Error("参数不能为null");

                //数据准备
                var operationData = obj.MapTo<BaseGoodsInputDto, BaseGoodsEntity>();
                operationData.UpdateId = GlobalUserManager.UserId;
                operationData.UpdateTime = DateTime.Now;
                operationData.AuditState = ProductStateConst.Offline;
                var result = await BaseGoodsRepository.AsUpdateable(operationData).IgnoreColumns(it => new { it.CreateTime, it.CreateId }).ExecuteCommandAsync();
                return GetResult.Success();
            }
            catch (Exception ex)
            {
                LoggerHelper.TryCatch(ex);
                return GetResult.Error(ex.Message);
            }
        }


        public async Task<ResultInfoModel> Audit(List<int> goodsIds, string auditResult, string auditRemark)
        {
            try
            {
                if (goodsIds == null || goodsIds.Count <= 0 || goodsIds.Any(a => a == 0))
                    return GetResult.Error("参数不能为null");

                //数据准备
                List<BaseGoodsEntity> baseGoods = new List<BaseGoodsEntity>();
                foreach (var goodId in goodsIds)
                {
                    BaseGoodsEntity operationData = new();
                    operationData.Id = goodId;
                    operationData.AuditUserId = GlobalUserManager.UserId;
                    operationData.AuditTime = DateTime.Now;
                    operationData.AuditState = auditResult;
                    operationData.AuditRemark = auditRemark;
                    baseGoods.Add(operationData);
                }
                var result = await BaseGoodsRepository.AsUpdateable(baseGoods)
                    .UpdateColumns(it => new
                    {
                        it.AuditUserId,
                        it.AuditTime,
                        it.AuditState,
                        it.AuditRemark
                    })
                    .ExecuteCommandAsync();
                return GetResult.Success();
            }
            catch (Exception ex)
            {
                LoggerHelper.TryCatch(ex);
                return GetResult.Error(ex.Message);
            }
        }


        public async Task<ResultInfoModel> UploadGoodsImageFile([FromForm] GoodsFileInputDto obj)
        {
            if (obj == null || obj.GoodsId == 0)
                return GetResult.Error("参数不能为null");
            string IDCardReversePath = string.Empty;
            if (obj.GoodsImages != null)
            {
                var upResult = await FileService.UploadFileAsync(obj.GoodsImages, Utils.Primitives.Class.UploadFile.UploadType.GoodsImages, obj.GoodsId.ToString(), true);
                if (upResult.IsSuccess)
                    IDCardReversePath = upResult.Message;
            }

            return GetResult.Success();
        }
    }
}
